package com.jack.lib.test.view

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.elvishew.xlog.XLog
import com.jack.lib.core.ext.toastW
import com.jack.lib.test.databinding.ActivityTestMainBinding
import com.lxj.xpopup.XPopup
import java.io.File
import java.nio.file.Files
import java.nio.file.attribute.BasicFileAttributes


/**
 * author : chong.huang
 * create : 2022/2/4
 * desc   :
 */
class TestMainActivity : AppCompatActivity() {


    private val binding by lazy { ActivityTestMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(binding.root)

        binding.changeHost.setOnClickListener {
            XPopup.Builder(this).asCustom(HostDialog(this)).show()
        }
        binding.log.setOnClickListener {
            openAndroidFile()
        }
        binding.deleteLog.setOnClickListener {
            val file = File(LogUtils.getConfig().defaultDir)
            if (file.isDirectory) {
                val lastFile = file.listFiles()?.maxByOrNull { it.lastModified() }?: return@setOnClickListener
                FileUtils.delete(lastFile)
            }
        }
    }

    private fun openAndroidFile(){
        val intent = Intent()
        val file = File(LogUtils.getConfig().defaultDir)
        if (file.isDirectory) {
            val lastFile = file.listFiles()?.maxByOrNull { it.lastModified() }?: return toastW("无log")
            intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val uri = FileProvider.getUriForFile(this, "$packageName.fileprovider", lastFile)
                intent.setDataAndType(uri, "text/plain")
            }else{
                intent.setDataAndType(Uri.fromFile(lastFile), "text/plain")
            }
            intent.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.action = Intent.ACTION_VIEW
            startActivity(intent)
        }

    }
}